package org.itheima.controller;


import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.itheima.pojo.LoginRequest;
import org.itheima.pojo.Result;
import org.itheima.pojo.User;
import org.itheima.service.UserService;
import org.itheima.utils.JwtUtil;
import org.itheima.utils.Md5Util;
import org.itheima.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

     @Autowired
     private UserService userService;


    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$")String password){
        /*if (username != null && username.length() >= 5 && username.length() <= 16
        && password != null && password.length() >= 5 && password.length() <= 16){*/

        System.out.println("Username: " + username);
        System.out.println("Password: " + password);

        User u = userService.findByUserName(username);

            if (u == null){
                //没有占用
                userService.register(username,password);
                return Result.success();
            }else{
                return Result.error("用户名已被占用");
            }
    } /*else{
            return Result.error("参数不合法");
        }*/

    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginRequest loginRequest){
        String username = loginRequest.getUsername();
        String password = loginRequest.getPassword();

        System.out.println("Username: " + username);
        System.out.println("Password: " + password);

        // 根据用户名查询用户
        User loginUser = userService.findByUserName(username);
        if (loginUser == null) {
            return Result.error("用户名错误");
        }

        // 判断密码是否正确
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    @CrossOrigin(origins = "http://localhost:3000")
    @GetMapping("/userInfo")
    public Result<User> UserInfo(/*@RequestHeader(name = "Authorization") String token*/){
        //根据用户查询用户
        /*Map<String,Object> map = JwtUtil.parseToken(token);
        String username = (String) map.get("username");*/
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public  Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params){
        //校验参数
        String oldPwd = params.get("oldPassword");
        String newPwd = params.get("newPassword");
        String rePwd = params.get("rePassword");

        System.out.println(oldPwd);
        System.out.println(newPwd);
        System.out.println(rePwd);

        if(!StringUtils.hasLength(oldPwd) /*|| StringUtils.hasLength(newPwd) || StringUtils.hasLength(rePwd)*/){
            return Result.error("缺少必要的参数1");
        }if(!StringUtils.hasLength(newPwd)){
            return Result.error("缺少必要的参数2");
        }if(!StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数3");
        }

        //原密码是否正确
        //调用userservice得到原密码
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);
        if (!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码不正确");
        }

        //newPwd和rePwd是否一样
        if (!rePwd.equals(newPwd)){
            return Result.error("两次填写新密码不一样");
        }

        //调用service完成密码更新
        userService.updatePwd(newPwd);
        System.out.println("真的改了");
        return Result.success();

    }

    @PutMapping("/updatePersonalIntroductionAndEmail")
    public Result updatePersonalIntroductionAndEmail(@RequestBody Map<String, String> request){
        String newBio = request.get("bio");
        String newEmail = request.get("email");
        System.out.println(newBio);
        System.out.println(newEmail);
        userService.updatePersonalIntroductionAndEmail(newBio, newEmail);
        return Result.success();
    }

    @PutMapping("/updateNickname")
    public Result updateNickname(@RequestBody Map<String, String> request){
        String newNickname = request.get("nickname");
        System.out.println(newNickname);
        userService.updateNickname(newNickname);
        return Result.success();
    }

    @GetMapping("/findAll")
    public List<Map<String,Object>> findAll(){
        System.out.println(userService.findAllOrdinary());
        return userService.findAllOrdinary();
    }

    @PutMapping("ban")
    public Result updateStatus(@RequestParam("userid") int userid){
        userService.updateStatus(userid);
        return Result.success();
    }


    @PutMapping("unban")
    public Result updateStatus2(@RequestParam("userid") int userid){
        System.out.println("userid是："+userid);
        userService.updateStatus2(userid);
        return Result.success();
    }


}
